package com.ossfk.jt808.pojo.resp;

import java.util.Arrays;

import org.apache.commons.lang3.StringUtils;

import com.ossfk.jt808.constant.Jt808Constants;
import com.ossfk.jt808.pojo.Jt808Msg;
import com.ossfk.net.session.TcpSession;
import com.ossfk.net.utils.ByteHelper;

import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @ClassName: Jt808TerminalRegistResp
 * @Description: 终端注册响应
 * @author Liujiefu
 * @date 2020-03-16 15:54:40
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class Jt808TerminalRegistResp extends Jt808Msg {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3954740308901267363L;
	/**
	 * 成功
	 */
	public static final byte SUCCESS = 0;
	/**
	 * 车辆已经注册
	 */
	public static final byte CAR_ALREADY_REGISTERED = 1;
	/**
	 * 车辆不存在
	 */
	public static final byte CAR_NOT_FOUND = 2;
	/**
	 * 终端已注册
	 */
	public static final byte TERMINAL_ALREADY_REGISTERED = 3;
	/**
	 * 终端不存在
	 */
	public static final byte TERMINAL_NOT_FOUND = 4;
	// byte[0-1] 应答流水号(WORD) 对应的终端注册消息的流水号
	private int replyFlowId;

	/***
	 * byte[2] 结果(BYTE) <br>
	 * 0：成功<br>
	 * 1：车辆已被注册<br>
	 * 2：数据库中无该车辆<br>
	 **/
	private byte replyCode;
	// byte[3-x] 鉴权码(STRING) 只有在成功后才有该字段
	private String replyToken;

	public Jt808TerminalRegistResp(TcpSession session, String phone) {
		super(session, Jt808Constants.CMD_COMMON_RESP);
	}

	public Jt808TerminalRegistResp(Jt808Msg packageData) {
		this.session = packageData.getSession();
		this.checkSum = packageData.getCheckSum();
		this.msgBodyBytes = packageData.getMsgBodyBytes();
		this.header = packageData.getHeader();
		this.msgBytes = packageData.getMsgBytes();
		decodeBody();
	}

	private void decodeBody() {
		this.replyFlowId = ByteHelper.byteToInteger(this.msgBodyBytes, 0, 2);
		this.replyCode = this.msgBodyBytes[2];
		byte[] replyTokenBytes = ByteHelper.subBytes(this.msgBodyBytes, 3, this.msgBodyBytes.length - 3);
		this.replyToken = new String(replyTokenBytes, Jt808Constants.STRING_CHARSET);
	}

	private byte[] encodeBody() {
		byte[] replyTokenBytes = null;
		if (StringUtils.isNotBlank(this.replyToken))
			replyTokenBytes = this.replyToken.getBytes(Jt808Constants.STRING_CHARSET);
		else
			replyTokenBytes = new byte[] {};
		this.msgBodyBytes = ByteHelper.concatAll(Arrays.asList(ByteHelper.integerTo2Bytes(this.replyFlowId),
				new byte[] { this.replyCode }, replyTokenBytes));
		return this.msgBodyBytes;
	}

	@Override
	public byte[] getMsgBodyBytes() {
		if (msgBodyBytes == null)
			encodeBody();
		return msgBodyBytes;
	}
}
